<template>
  <el-dialog v-model="visible" :title="`${!dataForm.id ? $t('add') : $t('update')}请假`" :close-on-click-modal="false"
    :close-on-press-escape="false" width="900">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <TitleBar title="请假人信息" />
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('leave.name')" prop="leavePersonIds" required v-if="!dataForm.id">
            <el-select v-model="dataForm.leavePersonIds" placeholder="请选择" multiple filterable @change="handleSelectStudent">
              <el-option v-for="item in studentList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('leave.name')" prop="name" required v-else>
            <el-input v-model="dataForm.name" placeholder="请输入" :disabled="dataForm.id"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('leave.typeName')" prop="typeId" required>
            <el-select v-model="dataForm.typeId" placeholder="请选择">
              <el-option v-for="item in leaveTypeList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('visitor.effectiveTime')" prop="time" required>
            <el-date-picker v-model="dataForm.time" type="datetimerange"
              :start-placeholder="$t('visitor.effectiveTime')" :end-placeholder="$t('visitor.expiryTime')"
              value-format="YYYY-MM-DD HH:mm:ss" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('leave.canReturnSchool')" prop="canReturnSchool" required>
            <el-switch v-model="dataForm.canReturnSchool" :active-value="1" :inactive-value="0" inline-prompt
              active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('leave.canReturnDormitory')" prop="canReturnDormitory" required>
            <el-switch v-model="dataForm.canReturnDormitory" :active-value="1" :inactive-value="0" inline-prompt
              active-text="是" inactive-text="否" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('leave.reason')" prop="reason" required>
            <el-input v-model="dataForm.reason" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="certificate" :label="$t('leave.certificate')">
            <ax-upload v-model="dataForm.certificate"></ax-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  name: "",
  canReturnDormitory: null,
  canReturnSchool: null,
  certificate: '',
  deviceInfoIds: [],
  time: [],
  effectiveTime: '',
  expiryTime: '',
  isEpidemic: '',
  reason: '',
  typeId: '',
  leavePersonIds: [] as string[],
  leavePersonInfos: [] as any[],
});

const rules = ref({
  name: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  time: [{ required: true, message: t("validate.required"), trigger: "change" }],
  reason: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  typeId: [{ required: true, message: t("validate.required"), trigger: "change" }],
  canReturnDormitory: [{ required: true, message: t("validate.required"), trigger: "change" }],
  canReturnSchool: [{ required: true, message: t("validate.required"), trigger: "change" }],
  leavePersonIds: [{ required: true, message: t("validate.required"), trigger: "change" }],
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getStudentList(), getLeaveTypeList()]).then(() => {
    if (id) {
      getInfo(id);
    }
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/leave/info/" + id).then((res) => {
    Object.assign(dataForm, res.data, { time: [res.data.effectiveTime, res.data.expiryTime] });
  });
};

// 获取学生列表
const studentList = ref<any[]>([]);
const getStudentList = () => {
  baseService.get("/data/personnel/student/page").then((res) => {
    studentList.value = res.data.list;
  });
};

// 获取请假类型列表
const leaveTypeList = ref<any[]>([]);
const getLeaveTypeList = () => {
  baseService.get("/leave/type/list").then((res) => {
    leaveTypeList.value = res.data;
  });
};

const handleSelectStudent = (vals: string[]) => {
  dataForm.leavePersonInfos = vals.map((v) => {
    const info = studentList.value.find((d: any) => d.id === v) || {};
    return {
      classId: info.classId,
      className: info.className || '0',
      name: info.name,
      personId: info.id,
      gender: info.gender,
      faceId: info.faceId || 123456,
      isInSchool: info.isInSchool,
    }
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService[!dataForm.id ? 'post' : 'put'](`/leave/info/${!dataForm.id ? 'save' : ''}`, {
      ...dataForm,
      effectiveTime: dataForm.time[0],
      expiryTime: dataForm.time[1],
    }).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
